package cn.exrick.xboot.modules.graphics.serviceimpl;

import cn.exrick.xboot.common.constant.CommonConstant;
import cn.exrick.xboot.common.exception.ServiceException;
import cn.exrick.xboot.factory.MyBeanFactory;
import cn.exrick.xboot.factory.methodRequest.RequestFactory;
import cn.exrick.xboot.modules.graphics.dao.mapper.ContainerMapper;
import cn.exrick.xboot.modules.graphics.entity.Container;
import cn.exrick.xboot.modules.graphics.entity.GraphicsContainer;
import cn.exrick.xboot.modules.graphics.enums.GraphicsPageExceptionEnum;
import cn.exrick.xboot.modules.graphics.param.ContainerListParam;
import cn.exrick.xboot.modules.graphics.param.ContainerParam;
import cn.exrick.xboot.modules.graphics.param.GraphicsPageParam;
import cn.exrick.xboot.modules.graphics.service.IContainerService;
import cn.exrick.xboot.modules.graphics.service.IGraphicsContainerService;
import cn.exrick.xboot.pojo.MethodRequest;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * 容器接口实现
 * @author njp
 */
@Slf4j
@Service
@Transactional
public class IContainerServiceImpl extends ServiceImpl<ContainerMapper, Container> implements IContainerService {

    @Autowired
    private IGraphicsContainerService iGraphicsContainerService;

    @Override
    public IPage<Container> page(ContainerParam containerParam, Page page) {
        LambdaQueryWrapper<Container> queryWrapper=new LambdaQueryWrapper();
        if(ObjectUtil.isNotNull(containerParam)){
            if(ObjectUtil.isNotEmpty(containerParam.getTitle())) {
                //根据标题模糊查询
                queryWrapper.like(Container::getTitle, containerParam.getTitle());
            }
        }
        //todo 只获取其数据范围的数据（后续添加）
        //查询未删除的
        queryWrapper.ne(Container::getDelFlag, CommonConstant.DEL_FLAG);
        queryWrapper.orderByDesc(Container::getUpdateTime);
        IPage page1 = this.page(page, queryWrapper);
        return page1;
    }

    @Override
    public List<Container> getList(ContainerParam containerParam) {
        LambdaQueryWrapper<Container> queryWrapper=new LambdaQueryWrapper();
        //todo 只获取其数据范围的数据（后续添加）
        //查询未删除的
        queryWrapper.ne(Container::getDelFlag, CommonConstant.DEL_FLAG);
        queryWrapper.orderByDesc(Container::getUpdateTime);
        return this.list(queryWrapper);
    }

    @Override
    public MethodRequest add(ContainerParam containerParam) {
        this.checkParam(containerParam,1,true);
        MethodRequest methodRequest=null;
        MyBeanFactory myBeanFactory=MyBeanFactory.getMyBeanFactory();
        Container container=myBeanFactory.createBean(Container.class);
        CopyOptions copyOptions=new CopyOptions();
        copyOptions.setIgnoreNullValue(true);
        BeanUtil.copyProperties(containerParam, container,copyOptions);
        boolean flag = this.save(container);
        if(flag){
            methodRequest = new RequestFactory().buildRequest(container, flag);
        }else {
            methodRequest = new RequestFactory().buildRequest(null, flag);
        }
        return methodRequest;
    }
    @Override
    public void delete(String containerId){
    //1.查询要删除的容器是否被引用了
        List<GraphicsContainer> gcList = iGraphicsContainerService.getGraphicsContainerListByContainerId(containerId);
        //2.没被引用可以删除，被引用不能被删除
        if(ObjectUtil.isNotEmpty(gcList)&&gcList.size()>0){
            throw new ServiceException(GraphicsPageExceptionEnum.CONTAINER_IS_USE_CANNOT_DELETE);

        }else{
            this.removeById(containerId);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void init(ContainerListParam containerListParam) {
        //1.先删除所有的容器（清空表）todo
            //1.1查询所有的容器
        List<Container> list = this.getList(new ContainerParam());
        list.forEach(c ->{
            this.delete(c.getId());
        });
        //2.新增容器 todo
        containerListParam.getDatas().forEach(cp->{
            this.add(cp);
        });


    }

    /**
     * njp
     * 校验参数，判断状态是否正确
     */
    private void checkParam(ContainerParam containerParam, int serviceType, boolean isExcludeSelf){
        switch (serviceType){
            case 1:
                if(ObjectUtil.isNotEmpty(containerParam)){
                    if(ObjectUtil.isEmpty(containerParam.getTitle())){
                        throw new ServiceException(GraphicsPageExceptionEnum.CONTAINER_PARAM_TITLE_ISNULL);
                    }else if(ObjectUtil.isEmpty(containerParam.getContent())){
                        throw new ServiceException(GraphicsPageExceptionEnum.CONTAINER_PARAM_CONTENT_ISNULL);
                    }
                }
        }
    }
}